<template>
  <div>
    <h1>Home</h1>
    <el-form ref="loginFormRef" :rules="loginFormRules" :model="loginForm" label-width="120px">
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="user_name">
        <el-input v-model="loginForm.user_name"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="userPwd">
        <el-input v-model="loginForm.userPwd" type="password"></el-input>
      </el-form-item>
      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="loginForm.phone"></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 登录按钮 -->
        <el-button type="primary" :loading="loginLoading" @click="submitForm">登录</el-button>
        <!-- 重置按钮 -->
        <el-button @click="loginFormRef.resetFields()">重置</el-button>
        <!-- 注册按钮 -->
        <el-button type="success" @click="$router.push('/register')">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="home">
  import { ref } from 'vue';
  import { login } from '@/api/login';
  const loginForm = ref({
    user_name: '',
    userPwd: '',
    phone: ''
  });
  const loginLoading = ref(false);

  const loginFormRules = {
    user_name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    userPwd: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ]
  };
  const loginFormRef: any = ref(null);

  const submitForm = () => {
    loginFormRef.value.validate((valid: boolean) => {
      if (valid) {
        loginLoading.value = true;
        login(loginForm.value)
          .then((res: any) => {
            console.log(res);
          })
          .catch((error) => {
            console.log(error);
          })
          .finally(() => {
            loginLoading.value = false;
          });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };
</script>

<style scoped></style>
